﻿(function() {
	(function($){
		$.namespace = function() {
		    var a=arguments, o=null, i, j, d;
		    for (i=0; i<a.length; i=i+1) {
		        d=a[i].split(".");
		        o=window;
		        for (j=0; j<d.length; j=j+1) {
		            o[d[j]]=o[d[j]] || {};
		            o=o[d[j]];
		        }
		    }
		    return o;
		};
	})(jQuery);
	
	(function($) {
	    $.QueryString = (function(a) {
	        if (a == "") return {};
	        var b = {};
	        for (var i = 0; i < a.length; ++i)
	        {
	            var p=a[i].split('=');
	            if (p.length != 2) continue;
	            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
	        }
	        return b;
	    })(window.location.search.substr(1).split('&'));
	})(jQuery);
	
	(function($){
		$.fn.serializeObject = function()
		{
		    var o = {};
		    var a = this.serializeArray();
		    $.each(a, function() {
		        if (o[this.name] !== undefined) {
		            if (!o[this.name].push) {
		                o[this.name] = [o[this.name]];
		            }
		            o[this.name].push(this.value || '');
		        } else {
		            o[this.name] = this.value || '';
		        }
		    });
		    return o;
		};
	})(jQuery);	
	jQuery.cachedScript = function(url, options) {
	  options = $.extend(options || {}, {
	    dataType: "script",
	    cache: true,
	    url: url
	  });
	  return jQuery.ajax(options);
	};
	$.loadBundleScripts = function(scripts,callback,scope,args){
		var arr = scripts;		
		while(arr.length > 0){
			var script = arr.pop();			
			$.getScript(script, function(data,textStatus) {
				if(textStatus != "success"){
					throw "loading script:" + script + " error.";
				}				
			});
		}
		if(callback && scope) {
			if(!args){
				args = [];
			}
			callback.apply(scope,args);
		}else if(callback) {
			callback();
		}
	};
	$.isiPad = function() {
		return  navigator.userAgent.match(/iPad/i) != null;
	};
	$.debugObj = function(obj) {
		var result = [];
		for(var p in obj){
			if(!$.isFunction(obj[p])){
				result.push(p +"=" + obj[p]);
			}
		}
		return result.join(",");
	};
	$.namespace("com.yogi.core");
	$.namespace("com.yogi.core.net");	
	$.namespace("com.yogi.runtime");
	
	com.yogi.core.loadCss = function(csss,cb,scope,version){
//		version = version || ( (Env && Env.CurrentConfig) ? Env.CurrentConfig["scriptversion"]:false);
//		var qs = version ? "?ver=" + version : "";
		var qs = "";
	    var head = document.getElementsByTagName('head').item(0);
	    //alert(head);
		while(csss.length > 0) {
			var css = document.createElement('link');
			css.href = csss.shift() + qs;
			css.rel = 'stylesheet';
			css.type = 'text/css';
			head.appendChild(css);
		}   //alert('loaded css!');
		cb.call(scope||window);
	};
	com.yogi.core.getFolderUrl = function(folder) {
		var virDir = window.contentPanel.getVirDir();
		if(virDir[virDir.length - 1] != '/') virDir += '/';
		return virDir + folder;
	};
	com.yogi.core.net.RemoteMethod = function(_serverUrl) {
		var serverUrl = _serverUrl;				
		function getParametersObject(MethodName,Parameters) {
			var data_obj = {
					CallbackMethod: MethodName
			};			
			$.each(Parameters, function(i,param){
				var key = "Parm" + (i+1).toString();
				var value = JSON.stringify(param);	//Ext.encode(param);
				data_obj[key] = value;
			});
			data_obj["CallbackParmCount"] = Parameters.length;
			return data_obj;
		}
		function doCallMethod(MethodName,Parameters, Callback, ErrorCallback ) {			
			var ajax_options = {
					cache: false,
					type: "POST",
					dataType: "json",
					data: getParametersObject(MethodName,Parameters),
					success: function(data, textStatus, jqXHR) {
						console.log("ajax call success");
						if(textStatus == "success") {
							if(Callback) Callback(data);
						} else {
							alert("网络故障");
						}
					},
					error: ErrorCallback || function(){ }
			};
			//error(jqXHR, textStatus, errorThrown)
			
			$.ajax(serverUrl, ajax_options);
		}
		var self = {
				callMethod: function(MethodName,Parameters, Callback, ErrorCallback) {
					return doCallMethod(MethodName,Parameters, Callback, ErrorCallback);
				}
		};
		return self;
	};
	com.yogi.core.net.YogiSmileRemoteMethod = function(_pluginId){
		function doCallMethod(MethodName,Parameters, Callback, ErrorCallback ) {		
			if(Parameters == null) Parameters = [];
			Parameters.unshift({YCBPI:_pluginId,Client:"flash"});							//加上这个参数
			var rm = new com.yogi.core.net.RemoteMethod(window.contentPanel.getVirDir() + ".admin.yogismile.ashx");
			rm.callMethod(MethodName,Parameters,Callback,ErrorCallback);
		}
		var self = {
				callMethod: function(MethodName,Parameters, Callback, ErrorCallback) {
					return doCallMethod(MethodName,Parameters, Callback, ErrorCallback);
				}
		};
		return self;
	};
	com.yogi.runtime.VisitStat = {
		serverUrl:"/Plugins/SiteStat/MakeStat.ashx",
		record: function(catalogId,virDir) {			
			$.get(virDir + this.serverUrl, {
				site:"main",
				first:catalogId
			});
		}
	};
	com.yogi.runtime.PageStack = function() {
		var m_pages = [];
		var m_active = null;
		var m_active_set = [];
		var m_tweening = false;
		
		function doHidePages(pages) {
			for(var i =0;i < m_pages.length;i++){
				if(pages.indexOf(m_pages[i]) < 0){
					$(m_pages[i]).hide();
				}
			}
		}
		function showPages(pages) {
			while(m_active_set.length > 0){
				m_active_set.pop();
			}
			for(var i = 0;i < pages.length;i++){
				m_active_set.push(pages[i]);
				$(pages[i]).show();
			}
		}	
		function showCurrentInTween(page ,tweenInTime ,previous ,fly_pos ) {	
			m_tweening = true;		
			for(var i =0;i < m_pages.length;i++){
				if(m_pages[i] != page && m_pages[i] != previous){
					$(m_pages[i]).hide();
				}
			} 
			m_active.visible = true;
			m_active.alpha = 0;		

			var new_active_x;
			var new_active_y;
			if(fly_pos != null){ 
				new_active_x = fly_pos[1][0];
				new_active_y = fly_pos[1][1];
				m_active.x = fly_pos[0][0];
				m_active.y = fly_pos[0][1];		//reset again
			}else{
				new_active_x = m_active.x;
				new_active_y = m_active.y;
			}	
			var tt;		
			if(tweenInTime instanceof Array){
				tt = tweenInTime[0];
			}else{
				tt = tweenInTime;
			}	
			$(m_active).css("display","block").animate({
				opacity:1,
				left: new_active_x,
				top: new_active_y
			}, tt, "easeInCubic", function(){
				m_tweening = false;
			});			
		}
		function doShowMultiPage(pages,tweenInTime) {
			if(!tweenInTime){		//不需要消隐						
				doHidePages(pages);		
				showPages(pages);				
			}else{		//需要消隐，算法是很不一样的
				if(m_active_set.length > 0){		//当前活动的要消隐	
					for(var i = 0;	i < m_active_set.length;i++){
						$(m_active_set[i]).fadeOut(tweenInTime);		
					}
				}
				while(m_active_set.length > 0){
					m_active_set.pop();
				}
				for(var j = 0; j < pages.length;j++){
					var p = pages[j];
					m_active_set.push(p);
					$(p).fadeIn(tweenInTime);
				}
			}
		}
		function doShowPage(page,tweenInTime,fly_pos) {
			if(!tweenInTime){		//不需要消隐
				m_active = page;
				for(var i =0;i < m_pages.length;i++){
					if(m_pages[i] != page){
						$(m_pages[i]).hide();
					}
				} 
				m_active.show();
			}else{		//需要消隐，算法是很不一样的
				var hide_time;
				var show_time;
				if(tweenInTime instanceof Array){
					hide_time = tweenInTime[0];
					show_time = tweenInTime[1]; 
				}else{
					hide_time = show_time = tweenInTime;
				}				
				var previous = m_active;
				m_active = page;
				if(previous != null){		//当前活动的要消隐
					var new_x;
					var new_y;
					if(fly_pos != null){ 
						new_x = fly_pos[2][0];
						new_y = fly_pos[2][1];
					}else{
						new_x = previous.x;
						new_y = previous.y;
					}
					m_tweening = true;
					
					$(previous).css('display', 'block');
					previous.animate({
						opacity: 0,
						left: new_x,
						top: new_y
					}, hide_time, "easeInCubic", function(){
						previous.visible = false;
						if(fly_pos != null){ 
							previous.x = fly_pos[0][0];
							previous.y = fly_pos[0][1];		//移动到反向
						}
						showCurrentInTween(page,show_time,previous,fly_pos);
					});
				}else{
					showCurrentInTween(page,show_time,previous,fly_pos);
				}						
			}
		}
		var _self = {
				addPage : function(page) {
					m_pages.push(page);
				},
				getActivePage: function( ) {
					return m_active;
				},
				getPage: function(index) {
					return m_pages[index];
				},
				showMultiPage: function(pages,tweenInTime) {
					doShowMultiPage(pages,tweenInTime);
				},
				showPage: function(page,tweenInTime,fly_pos) {						
					doShowPage(page,tweenInTime,fly_pos);
				},
				hidePages: function (pages) {
					doHidePages(pages);
				}
		};
		return _self;
	};	
	com.yogi.core.EVENT_EXTERNAL_SCRIPT_LOADED = "external_script_loaded";
	com.yogi.core.startup = function( config ){
		var base_path = config.base_path;
		
		var scripts = [base_path + "core/FlexPage.js",
		               base_path + "core/FlexPart.js",
		               base_path + "core/ResourceBundle.js",
		               base_path + "core/WrapperManager.js",
		               base_path + "core/ContentPanel.js"];
		var core_scripts_to_load = [ "com.yogi.core.FlexPage","com.yogi.core.FlexPart","com.yogi.core.ResourceBundle","com.yogi.core.WrapperManager","com.yogi.core.ContentPanel" ];
		var amount_script_to_load = core_scripts_to_load.length; 
		var amount_script_loaded = 0;
		var on_external_script_loaded = function(e,data) {
			var script = data.script;
			if(core_scripts_to_load.indexOf(script) >= 0){
				amount_script_loaded ++;
				if(amount_script_loaded == amount_script_to_load){
					do_startup();
				}
			}			
		};
		
		var do_startup = function(){
			$(window).unbind(com.yogi.core.EVENT_EXTERNAL_SCRIPT_LOADED, on_external_script_loaded );
			var sw = $(window).width();
			var sh = $(window).height();			
			var _config = {
					stage_width: sw,
					stage_height: sh,
					ct:document.body
			};
			$.extend(_config, config || {});
			var cp = new com.yogi.core.ContentPanel( _config.query_string );
			window.contentPanel = cp;
			
			window.HYPE_DocumentsToLoad = new Array();
			window.HYPE_100_DocumentsToLoad = new Array();
			cp.init(_config);
		};
		$(window).bind(com.yogi.core.EVENT_EXTERNAL_SCRIPT_LOADED,  on_external_script_loaded);		
//		if(Ext.isIE6) {
//			loadScript(scripts);
//		}else{
//			$.loadBundleScripts(scripts);
//		}		
		$.loadBundleScripts(scripts);
	};	
	$(window).trigger("kernel_executed");
})();